package org.hr.xtime

import java.util.Date;

import org.hr.organisation.OrganisationService;
import org.hr.organisation.UserDetails;
import org.hr.xtime.absence.Day;
import org.hr.xtime.absence.DayType;
import org.hr.xtime.user.Employee;

class AbsenceService {
	
	OrganisationService organisationService

    boolean isAvailable(String userId, Date date) {
		Employee e = Employee.findByUserId(userId)
		List l = Day.findAllByEmployeeAndDate(e,date)
		return (l.count==0)
    }
	
	Employee getApprover(def userId, Date date){
		UserDetails bossDetails = organisationService.getBoss(userId)
		Employee boss = Employee.findByUserId(bossDetails.userId)
		if (isAvailable(boss.userId,date)) {
			return boss
		}else{	
			return Employee.findByUserId(boss.standIn)
		}
	}
	
	Map calculateBalance(Employee employee, Date fromDate, Date toDate ){
		Map balance = [:]
		DayType.list().each{dayType->
				balance.put(dayType.key, 0.0)
		}
		List<Day> days = Day.findAllByEmployeeAndDateBetween(employee,fromDate,toDate)
		days.each{day->
			def hours = balance.get(day.type.key) + day.hours
			balance.put(day.type.key, hours)
		}
		return balance
		
	}
}
